package cn.sinokj.party.chineseFourParty.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;

import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.DiscussedListActivity;
import cn.sinokj.party.chineseFourParty.activity.ExamResultListActivity;
import cn.sinokj.party.chineseFourParty.activity.MainActivity;
import cn.sinokj.party.chineseFourParty.activity.MyBookMoneyActivity;
import cn.sinokj.party.chineseFourParty.activity.MyMembershipMoneyActivity;
import cn.sinokj.party.chineseFourParty.activity.PocketTutorResultActivity;
import cn.sinokj.party.chineseFourParty.activity.SettingActivity;
import cn.sinokj.party.chineseFourParty.activity.VoteListActivity;
import cn.sinokj.party.chineseFourParty.app.App;
import cn.sinokj.party.chineseFourParty.bean.MineInfo;
import cn.sinokj.party.chineseFourParty.fragment.base.BaseFragment;
import cn.sinokj.party.chineseFourParty.service.HttpDataService;
import cn.sinokj.party.chineseFourParty.utils.Constans;
import cn.sinokj.party.chineseFourParty.utils.UIUitls;
import cn.sinokj.party.chineseFourParty.view.dialog.DialogShow;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.utils.AndroidLifecycleUtils;

/**
 * Created by l on 2017/11/12.
 */

public class MineFragment extends BaseFragment {
    private static final int UPLOAD_IMAGE = 0;
    private static final int INIT_DATA = 1;
    @BindView(R.id.mine_face)
    public RoundedImageView faceImage;
    @BindView(R.id.mine_name)
    public TextView nameText;
    @BindView(R.id.mine_degree)
    public TextView degreeText;
    @BindView(R.id.tv_progress)
    public TextView tvProgress;
    @BindView(R.id.vcDept)
    TextView mVcDept;
    @BindView(R.id.ll_star_contaner)
    LinearLayout llStarContaner;
    private MineInfo mineInfo;
    private MainActivity activity;
    private String picPath;
    private View mMineView;
    private String headImage;
    private ImmersionBar mImmersionBar;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        mMineView = inflater.inflate(R.layout.fragment_mine, container, false);
        ButterKnife.bind(this, mMineView);
        EventBus.getDefault().register(this);
        initImmersionBar();
        activity = (MainActivity) getActivity();
        DialogShow.showRoundProcessDialog(getActivity());
        new Thread(new LoadDataThread(INIT_DATA)).start();
        return mMineView;
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(Message msg) {
        switch (msg.what) {
            case Constans.MINE_REFRESH:
                refreshView();
                break;
        }
    }

    private void refreshView() {
        if (mMineView != null) {
            mMineView.setVisibility(View.INVISIBLE);
        }
        new Thread(new LoadDataThread(INIT_DATA)).start();
    }

    @Override
    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            case UPLOAD_IMAGE:
                return HttpDataService.updateHeadImg(picPath);
            case INIT_DATA:
                return HttpDataService.getAllMyInfo();
        }
        return super.getDataFunction(what, arg1, arg2, obj);
    }

    @Override
    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        switch (msg.what) {
            case UPLOAD_IMAGE:
                break;
            case INIT_DATA:
                mMineView.setVisibility(View.VISIBLE);
                String s = jsonObject.toString();
                Gson gson = new Gson();
                mineInfo = gson.fromJson(s, MineInfo.class);
                App.MINE_REFRESH = false;
                initializeViews();
                break;
        }
        DialogShow.closeDialog();
    }

    private void initializeViews() {
        if (!TextUtils.isEmpty(mineInfo.getBaseInfo().getVcHeadImgUrl())) {
            Glide.with(this)
                    .load(mineInfo.getBaseInfo().getVcHeadImgUrl())
                    .centerCrop()
                    .error(R.drawable.face)
                    .into(faceImage);
        } else {
            faceImage.setImageDrawable(null);
        }
        nameText.setText(mineInfo.getBaseInfo().getVcName());
        degreeText.setText(mineInfo.getLevel().getVcLevel());

        llStarContaner.removeAllViews();
        int margin = UIUitls.dip2px(getContext(),5);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for (int i = 0; i < 6; i++) {
            ImageView imageView = new ImageView(getContext());
            if (i < mineInfo.getLevel().getNLevel()){
                imageView.setImageResource(R.drawable.icon_star_sel);
            }else {
                imageView.setImageResource(R.drawable.icon_star_nor);
            }
            params.setMargins(0,margin,margin,margin);
            llStarContaner.addView(imageView,params);
        }

        tvProgress.setText(mineInfo.getNLevelPoint() + "");
      /*  String vcDeptName;
        if (mineInfo.getBaseInfo().getVcDeptName().length() > 9) {
            vcDeptName = mineInfo.getBaseInfo().getVcDeptName().substring(0, 9) + "\n" +
                    mineInfo.getBaseInfo().getVcDeptName().substring(9, mineInfo.getBaseInfo().getVcDeptName().length());
        } else {
            vcDeptName = mineInfo.getBaseInfo().getVcDeptName();
        }
        vcDeptName.replace("\\n", "\n");*/
        mVcDept.setText(mineInfo.getBaseInfo().getVcDeptName());
    }


    @OnClick({R.id.mine_face, R.id.mine_vote, R.id.mine_study, R.id.mine_answer, R.id
            .mine_discussion, R.id.mine_setting, R.id.mine_money, R.id.mine_membership_money, R.id.mine_mybookmoney})
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.mine_face:
                PhotoPicker.builder()
                        .setPhotoCount(1)
                        .setShowCamera(true)
                        .setShowGif(true)
                        .setPreviewEnabled(false)
                        .start(activity, PhotoPicker.REQUEST_CODE);
                break;
            case R.id.mine_vote:
                intent.setClass(activity, VoteListActivity.class);
                intent.putExtra("voted", true);
                startActivity(intent);
                break;
            case R.id.mine_study:
                if (mineInfo != null) {
                    intent.setClass(activity, PocketTutorResultActivity.class);
                    intent.putExtra("functionType", "我的学习");
                    intent.putExtra("score", mineInfo.getBaseInfo().getNPocketTutorPoint());
                    startActivity(intent);
                }
                break;
            case R.id.mine_answer:
                if (mineInfo != null) {
                    intent.setClass(activity, ExamResultListActivity.class);
                    intent.putExtra("functionType", "我的答题");
                    intent.putExtra("examTopics", (Serializable) mineInfo.getPalmExam());
                    startActivity(intent);
                }
                break;
            case R.id.mine_discussion://我的评议
                if (mineInfo != null) {
                    intent.setClass(activity, DiscussedListActivity.class);
                    intent.putExtra("discussedList", (Serializable) mineInfo.getDiscussions());
                    startActivity(intent);
                }
                break;
            case R.id.mine_setting:
                if (mineInfo != null) {
                    intent.setClass(activity, SettingActivity.class);
                    intent.putExtra("about", mineInfo.getAbout());
                    startActivity(intent);
                }
                break;
            case R.id.mine_money:
                Toast.makeText(activity, "敬请期待", Toast.LENGTH_SHORT).show();
                break;
            case R.id.mine_membership_money:
                intent.setClass(activity, MyMembershipMoneyActivity.class);
                startActivity(intent);
                break;

            case R.id.mine_mybookmoney:
                intent.setClass(activity, MyBookMoneyActivity.class);
                startActivity(intent);
                break;
        }
    }

    public void setHeadImage(String picPath) {
        this.picPath = picPath;
        Uri uri = Uri.fromFile(new File(picPath));
        boolean canLoadImage = AndroidLifecycleUtils.canLoadImage(this);
        if (canLoadImage) {
            Glide.with(this)
                    .load(uri)
                    .asBitmap()
                    .centerCrop()
                    .error(R.drawable.face)
                    .into(faceImage);
        }
    }

    public void upLoadImage() {
        new Thread(new LoadDataThread(UPLOAD_IMAGE)).start();
    }

    protected void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.keyboardEnable(true).navigationBarWithKitkatEnable(false).init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mImmersionBar != null)
            mImmersionBar.destroy();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            new Thread(new LoadDataThread(INIT_DATA)).start();
            DialogShow.showRoundProcessDialog(getActivity());
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
